package spzx.service.impl;

import com.atguigu.spzx.model.dto.product.CategoryBrandDto;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.entity.product.CategoryBrand;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import spzx.exception.SpzxException;
import spzx.mapper.CategoryBrandMapper;
import spzx.mapper.CategoryMapper;
import spzx.service.CategoryBrandService;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryBrandServiceImpl implements CategoryBrandService {

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public PageInfo findByPage(Integer pageNum, Integer pageSize, CategoryBrandDto categoryBrandDto) {
        PageHelper.startPage(pageNum, pageSize);
        List<CategoryBrand> list = categoryBrandMapper.selectList(categoryBrandDto);
        return new PageInfo(list);
    }

    @Override
    public void addCategoryBrand(CategoryBrand categoryBrand) {
        //1.校验此对应关系是否存在
        CategoryBrand c = categoryBrandMapper.selectCategoryBrand(categoryBrand);
        if(c != null){
            throw new SpzxException(501,"分类品牌已存在,请勿重复创建");
        }
        //2.新建
        categoryBrandMapper.addCategoryBrand(categoryBrand);
    }

    @Override
    public List<Long> findCategoryIds(Long category3Id) {
        //[1,2,3级标题]
        List<Long> list = new ArrayList<>();

        //根据第三级分类id查询第三级分类对象
        Category three = categoryMapper.getById(category3Id);
        Long twoId = three.getParentId();
        //根据第二级分类id查询第二级分类对象
        Category two = categoryMapper.getById(twoId);
        Long oneId = two.getParentId();

        list.add(oneId);
        list.add(twoId);
        list.add(category3Id);
        return list;
    }

    @Override
    public void updateCategoryBrand(CategoryBrand categoryBrand) {
        CategoryBrand c = categoryBrandMapper.selectCategoryBrand(categoryBrand);

        if(c != null) {
            if (c.getId() == categoryBrand.getId()) {
                throw new SpzxException(501, "数据未发生改变，修改后重新提交");
            } else {
                throw new SpzxException(501, "此关系数据已存在！");
            }
        }

        categoryBrandMapper.updateCategoryBrand(categoryBrand);
    }

    @Override
    public void deleteById(Long id) {
        categoryBrandMapper.deleteById(id);
    }
}
